# -*- coding: utf-8 -*-
#
# Copyright 2017 zhangxp, st
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import socket
from rqalpha.interface import AbstractMod
from rqalpha.utils.logger import user_system_log, user_log

from .stu_log import LogHandler


class CustomLogHandlerMod(AbstractMod):
    def __init__(self):
        self._s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._addr = None

    def __del__(self):
        self._s.close()

    def _send_log(self, dt, text, log_tag):
        if self._addr is not None:
            self._s.sendto((log_tag + text).encode(), self._addr)
        pass

    def start_up(self, env, mod_config):
        user_log.handlers.append(LogHandler(self._send_log, bubble=True))
        # 不配置不启动
        if 'ip' in mod_config and 'port' in mod_config:
            self._addr = (mod_config.ip, mod_config.port)
        elif 'ip' in mod_config:
            self._addr = (mod_config.ip, 6000)

    def tear_down(self, code, exception=None):
        pass

